<template>
  <div>
    <h1>活动管理列表</h1>
    <el-button type="info" @click="ShowActiveList()">添加活动</el-button>
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="activeId" label="活动id" />
      <el-table-column prop="activeName" label="活动名称" />
      <el-table-column prop="payScore" label="库存" />
      <el-table-column prop="beginTime" label="开始时间" />
      <el-table-column prop="endTime" label="截止时间" />
      <el-table-column prop="joinUser" label="参与用户" />
      <el-table-column prop="freeTimes" label="活动免费抽奖次数" />
      <el-table-column prop="typeName" label="奖品类型" />
      <el-table-column prop="winUser" label="中奖名单" />
      <el-table-column prop="winList" label="中奖记录" />
      <el-table-column prop="activeStatus" label="活动状态" />
      <el-table-column prop="activeContent" label="活动规则">
        <template #default="scope">
          <span v-html="scope.row.activeContent"></span>
        </template>
      </el-table-column>
      <el-table-column prop="createBy" label="创建人" />
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column prop="updateBy" label="更新人" />
      <el-table-column prop="updateTime" label="更新时间" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="success" @click="ShowUpdateActive(scope.row)"
            >修改</el-button
          >
          <el-button type="danger" @click="OnDeleteActiveList(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="demo-pagination-block">
      <div class="demonstration"></div>
      <el-pagination
        v-model:current-page="listFrom.pageNum"
        v-model:page-size="listFrom.pageSize"
        :page-sizes="[2, 4, 6, 8]"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 添加活动 -->
    <div>
      <el-dialog v-model="dialogFormVisible" title="添加活动页面" width="1000">
        <el-form
          :model="form"
          class="demo-form-inline"
          :inline="true"
          ref="ruleFormRef"
          :rules="rules"
        >
          <el-form-item
            label="活动名称"
            :label-width="formLabelWidth"
            prop="activeName"
          >
            <el-input v-model="form.activeName" autocomplete="off" />
          </el-form-item>
          <el-form-item
            label="库存"
            :label-width="formLabelWidth"
            prop="payScore"
          >
            <el-input-number
              v-model="form.payScore"
              :min="1"
              :max="1000000"
              @change="handleChange"
            />
          </el-form-item>
          <el-form-item
            label="活动时间"
            :label-width="formLabelWidth"
            prop="getTimeList"
          >
            <el-date-picker
              v-model="form.getTimeList"
              type="datetimerange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              date-format="YYYY/MM/DD ddd"
              time-format="A hh:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item
            label="参与用户"
            :label-width="formLabelWidth"
            prop="userFlag"
          >
            <el-select
              v-model="form.userFlag"
              placeholder="请选择参与用户"
              style="width: 240px"
            >
              <el-option
                v-for="item in userFlagList"
                :key="item.dictValue"
                :label="item.dictName"
                :value="item.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="奖品类型"
            :label-width="formLabelWidth"
            prop="winType"
          >
            <el-select
              v-model="form.winType"
              placeholder="请选择奖品类型"
              style="width: 240px"
            >
              <el-option
                v-for="item in winTypeList"
                :key="item.dictValue"
                :label="item.dictName"
                :value="item.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="中奖名单"
            :label-width="formLabelWidth"
            prop="winFlag"
          >
            <el-select
              v-model="form.winFlag"
              placeholder="请选择中奖名单"
              style="width: 240px"
            >
              <el-option
                v-for="item in winFlagList"
                :key="item.dictValue"
                :label="item.dictName"
                :value="item.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="中奖记录"
            :label-width="formLabelWidth"
            prop="winRecord"
          >
            <el-select
              v-model="form.winRecord"
              placeholder="请选择中奖记录"
              style="width: 240px"
            >
              <el-option
                v-for="item in winRecordList"
                :key="item.dictValue"
                :label="item.dictName"
                :value="item.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="活动规则"
            :label-width="formLabelWidth"
            prop="activeContent"
          >
            <div style="border: 1px solid #ccc">
              <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :defaultConfig="toolbarConfig"
                :mode="mode"
              />
              <Editor
                style="height: 500px; overflow-y: hidden"
                v-model="form.activeContent"
                :defaultConfig="editorConfig"
                :mode="mode"
                @onCreated="handleCreated"
              />
            </div>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
              添加
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
    <!-- 修改活动 -->
    <div>
      <el-dialog v-model="dialogTableVisible" title="修改活动页面" width="1000">
        <el-form :model="form" class="demo-form-inline" :inline="true">
          <el-form-item label="活动名称" :label-width="formLabelWidth">
            <el-input v-model="form.activeName" autocomplete="off" />
          </el-form-item>
          <el-form-item label="库存" :label-width="formLabelWidth">
            <el-input v-model="form.payScore" autocomplete="off" />
          </el-form-item>
          <el-form-item label="开始时间" :label-width="formLabelWidth">
            <el-date-picker
              v-model="form.beginTime"
              type="datetime"
              placeholder="请选择开始时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="截止时间" :label-width="formLabelWidth">
            <el-date-picker
              v-model="form.endTime"
              type="datetime"
              placeholder="请选择截止时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="参与用户" :label-width="formLabelWidth">
            <el-input v-model="form.joinUser" autocomplete="off" />
          </el-form-item>
          <el-form-item label="奖品类型" :label-width="formLabelWidth">
            <el-input v-model="form.typeName" autocomplete="off" />
          </el-form-item>
          <el-form-item label="中奖名单" :label-width="formLabelWidth">
            <el-input v-model="form.winUser" autocomplete="off" />
          </el-form-item>
          <el-form-item label="中奖记录" :label-width="formLabelWidth">
            <el-input v-model="form.winList" autocomplete="off" />
          </el-form-item>
          <el-form-item label="活动规则" :label-width="formLabelWidth">
            <div style="border: 1px solid #ccc">
              <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :defaultConfig="toolbarConfig"
                :mode="mode"
              />
              <Editor
                style="height: 500px; overflow-y: hidden"
                v-model="form.activeContent"
                :defaultConfig="editorConfig"
                :mode="mode"
                @onCreated="handleCreated"
              />
            </div>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="OnUpdateActiveList()">
              修改
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { onMounted, reactive, ref } from "vue";
import {
  getActiveList,
  getDictList,
  addActive,
  updateActiveList,
  deleteActiveList,
} from "../api/api";
import type { FormInstance, FormRules } from "element-plus";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { onBeforeUnmount, shallowRef } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { ElMessage, ElMessageBox } from "element-plus";
const dialogTableVisible = ref(false);
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const ruleFormRef = ref<FormInstance>();
const tableData = ref([]);
const winFlagList = ref([]);
const winRecordList = ref([]);
const winTypeList = ref([]);
const userFlagList = ref([]);
const total = ref(0);
const mode = "default";
const listFrom = ref({
  pageNum: 1,
  pageSize: 2,
});
const form = ref({
  activeContent: "",
  activeId: null,
  activeName: "",
  activeStatus: null,
  beginTime: "",
  createBy: "",
  createTime: "",
  endTime: "",
  freeTimes: null,
  joinUser: "",
  payScore: null,
  statusName: "",
  typeName: "",
  updateBy: "",
  updateTime: "",
  userFlag: null,
  winFlag: null,
  winList: "",
  winRecord: null,
  winType: null,
  winUser: "",
  getTimeList: [],
});
const list = () => {
  getActiveList(listFrom.value).then((res) => {
    if (res.data.code == 200) {
      tableData.value = res.data.data.records;
      total.value = res.data.data.total;
    }
  });
};
//分页
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  listFrom.value.pageSize = val;
  list();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  listFrom.value.pageNum = val;
  list();
};
//添加活动
const ShowActiveList = () => {
  dialogFormVisible.value = true;
};
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      addActive(form.value).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("用户添加成功!");
          dialogFormVisible.value = false;
          list();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};
//修改
const ShowUpdateActive = (row: any) => {
  form.value = row;
  dialogTableVisible.value = true;
};
const OnUpdateActiveList = () => {
  updateActiveList(form.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("用户修改成功!");
      dialogTableVisible.value = false;
      list();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};
//删除
const OnDeleteActiveList = (row: any) => {
  ElMessageBox.confirm("请您三思啊,您确定要删除吗?", "删除严重警告框", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "error",
  })
    .then(() => {
      deleteActiveList(row.activeId).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("用户删除成功!");
          list();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "用户取消删除啦！",
      });
    });
};
//校验
const rules = reactive<FormRules>({
  activeName: [{ required: true, message: "请输入活动名称", trigger: "blur" }],
  payScore: [{ required: true, message: "请选择库存", trigger: "blur" }],
  getTimeList: [{ required: true, message: "请选择活动时间", trigger: "blur" }],
  userFlag: [{ required: true, message: "请选择参与活动", trigger: "blur" }],
  winType: [{ required: true, message: "请选择商品类型", trigger: "blur" }],
  winFlag: [{ required: true, message: "请选择中奖名单", trigger: "blur" }],
  winRecord: [{ required: true, message: "请选择中奖记录", trigger: "blur" }],
  activeContent: [
    { required: true, message: "请输入活动规则", trigger: "blur" },
  ],
});
//数字输入框
const handleChange = (value: number | undefined) => {
  console.log(value);
};
//富文本
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 内容 HTML
const valueHtml = ref("<p>hello</p>");

// 模拟 ajax 异步获取内容
onMounted(() => {
  setTimeout(() => {
    valueHtml.value = "<p>模拟 Ajax 异步设置内容</p>";
  }, 1500);
});

const toolbarConfig = {};
const editorConfig = { placeholder: "请输入内容..." };

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};
onMounted(() => {
  list();
  getDictList(5).then((res) => {
    if (res.data.code == 200) {
      userFlagList.value = res.data.data;
    }
  });
  getDictList(13).then((res) => {
    if (res.data.code == 200) {
      winTypeList.value = res.data.data;
    }
  });
  getDictList(6).then((res) => {
    if (res.data.code == 200) {
      winFlagList.value = res.data.data;
    }
  });
  getDictList(6).then((res) => {
    if (res.data.code == 200) {
      winRecordList.value = res.data.data;
    }
  });
});
</script>
<style scoped>
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
</style>
